import axios from 'axios'
import { Toast } from 'vant';
import store from '../store'
import zVue from '../main.js'
import { getTypeAndAddress } from "@/common/connectWallet";
const service = axios.create({
    baseURL: '/api',
    timeout: 30000
})
service.interceptors.request.use(
    config => {
        config.headers = {
            // 'Content-Type': 'application/x-www-form-urlencoded'
            'Content-Type': 'application/json' //配置请求头
        }
        const flag = config.url.includes('user/login')
        const userInfo = store.getters && store.getters.getUserInfo
        flag ? config.headers["Authorization"] = `Basic ZGFwcDpkYXBw` : (
            userInfo.access_token && (config.headers["Authorization"] = `Bearer ${userInfo.access_token}`)
        )
        let locale = localStorage.getItem('lang') || 'zh_CN'
        config.headers["Dapp-Accept-Language"] = locale
        // Toast.loading({
        //     message: '',
        //     duration: 0
        // });
        return config
    },
    error => {
        console.log(error);
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response => {
        Toast.clear()
        const res = response
        if (res.data.code === 0) {
            return res
        } else {
            Toast(res.data.msg || zVue.$t('long.fuwuqicuowu'))
            return res
        }
    },
    async (error) => {
        Toast.clear()
        const res = error.response && error.response.data
        let rurl = error.config.url
        if(rurl&&(rurl.includes('getArticleManagement') || rurl.includes('userToUnreadNumber'))){
           return 
        }
        if (res.code === 1 && res.data && res.data.includes('Invalid token')) {
            Toast(zVue.$t('long.yonghuxinxishi'))
            store.commit('removeUserInfo')
            const ret = await getTypeAndAddress();
            if (ret != false) {
                console.log(ret)
                store.commit("setUserInfo", ret);
                window.location.reload();
            }
        } else {
            Toast(res.msg || zVue.$t('long.fuwuqicuowu'))
        }
    }
)
export default service
